package com.lagou.rpc.regist;

import com.lagou.util.LongByteUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * @ClassName RpcRegister
 * @Description Rpc服务端注册器
 * @Author playboy
 * @Date 2021/6/8 2:36 下午
 * @Version 1.0
 **/
@Component
@ConfigurationProperties(prefix = "spring.zookeeper")
public class RpcRegister implements InitializingBean, DisposableBean {

	private String address;

	private CuratorFramework client;

	private String path = "/rpc/servers";

	public void setAddress(String address) {
		this.address = address;
	}

	/**
	 * 向zookeeper注册/rpc/servers/server注册临时顺序节点
	 */
	public void register(String addr) {
		try {
			client.create()
					.creatingParentsIfNeeded()
					.withMode(CreateMode.EPHEMERAL)
					.forPath(path + File.separator + addr, LongByteUtil.longToBytes(0L));
			System.out.println(addr + "注册服务成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		//在这里进行zookeeper的连接
		ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 3);
		client = CuratorFrameworkFactory.builder()
				.connectString(address)
				.sessionTimeoutMs(50000)
				.connectionTimeoutMs(30000)
				.retryPolicy(retryPolicy)
				.build();
		client.start();

	}

	@Override
	public void destroy() throws Exception {
		System.out.println("服务端与zookeeper连接断开");
		client.close();
	}
}